/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author mwh
 */
public class TranslationTableCache implements TranslationTable {

    TranslationTable table;

    Map<Integer, Map<Integer, Double>> cache;


    public TranslationTableCache(TranslationTable table, int size) {
        this.table = table;

        final long maxsize = Math.round(size*0.80);
        
        cache = new LinkedHashMap<Integer, Map<Integer, Double>>(size, 0.75F, true) {

            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Map<Integer, Double>> eldest) {
                return size() > maxsize;
            }
        };
    }


    public double get(Integer source, Integer target) {

        Map<Integer, Double> translations = get(source);

        if (source.equals(1)) {
            return 0.00001;
        }
        if (translations.containsKey(target)) {
            return translations.get(target);
        } else {
            return translations.get(-1024);
        }
    }


    public double getLog10(int source, int target) {
        return Math.log10(get(source, target));
    }


    public Map<Integer, Double> get(Integer source) {
        Map<Integer, Double> translations = cache.get(source);
        if (translations == null) {
            translations = table.get(source);
            cache.put(source, translations);
        }
        return translations;
    }
}
